import { queryCurrent, query as queryUsers, login } from '@/services/user';

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    userInfo: {}
  },
  effects: {

    // 登陆
    *login({ payload }, { call, put }) {
      const response = yield call(login, payload)
      // return
      if (response.Status === 1 && response.User && response.User.IsRoot) {
        sessionStorage.setItem('userInfo', JSON.stringify(response.User))
        
        yield put({
          type: 'saveUserInfo',
          payload: response,
        })

        return {status: 200}
      }
        return {status: 500}
    },

    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },

    saveUserInfo(state, { payload }) {
      return { ...state, userInfo: payload.User };
    },

    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
